package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.commom.UserHolder;
import com.itheima.reggie.domain.Cart;
import com.itheima.reggie.mapper.CartMapper;
import com.itheima.reggie.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;


// 购物车
@Service
@Transactional
public class CartServiceImpl implements CartService {
@Autowired
private CartMapper cartMapper;
        @Override
        public Cart add(Cart cart) {
            //查询是否有次购物项
            LambdaQueryWrapper<Cart> qw = new LambdaQueryWrapper<>();
            //用户id
            Long userId = UserHolder.get().getId();
            qw.eq(Cart::getUserId, userId);
            //菜品id
            qw.eq(cart.getDishId() != null, Cart::getDishId, cart.getDishId());
            //套餐id
            qw.eq(cart.getSetmealId() != null, Cart::getSetmealId, cart.getSetmealId());
            //执行查询
            Cart cart1 = cartMapper.selectOne(qw);
            //比较
            if (cart1 != null) {
                cart1.setNumber(cart1.getNumber()+1);
                cartMapper.updateById(cart1);
            }else {
                cart1=cart;
                cart1.setUserId(userId);
                cart1.setNumber(1);
                cart1.setCreateTime(new Date());
                cartMapper.insert(cart1);
            }
            //返回购物车
            return cart1;
        }

    @Override
    public List<Cart> list() {
        LambdaQueryWrapper<Cart> qw = new LambdaQueryWrapper<>();
       qw.eq(Cart::getUserId,UserHolder.get().getId());
       return cartMapper.selectList(qw);
        }

    @Override
    public void deleteList() {
        LambdaQueryWrapper<Cart> qw1 = new LambdaQueryWrapper<>();
        qw1.eq(Cart::getUserId,UserHolder.get().getId());
      cartMapper.delete(qw1);
    }

    @Override
    public Cart sub(Cart cartParam) {
        // 1.先查询购物车
        LambdaQueryWrapper<Cart> qw = new LambdaQueryWrapper<>();
        // 用户id
        qw.eq(Cart::getUserId, UserHolder.get().getId());
        // 套餐id 动态sql
        qw.eq(cartParam.getSetmealId() != null, Cart::getSetmealId, cartParam.getSetmealId());
        // 菜品id 动态sql
        qw.eq(cartParam.getDishId() != null, Cart::getDishId, cartParam.getDishId());
        Cart cart = cartMapper.selectOne(qw);

        // 2.购物数量-1
        cart.setNumber(cart.getNumber()-1);

        // 3.判断数量是否为0
        if (cart.getNumber()==0) {
            // 删除购物车
            cartMapper.deleteById(cart.getId());
        }else{
            // 更新购物车
            cartMapper.updateById(cart);
        }
        // 4.返回购物车
        return cart;
    }




}

